import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';

import {Observable} from 'rxjs/Rx';
import {AuthLoginComponent} from './auth-login/auth-login.component';
import {AuthUserService} from './auth-user.service';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router,
                private authUserService: AuthUserService) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

        let user = null;
        this.authUserService.getCurrentUser().subscribe(data => {
            user = data;
        });

        if (/\/todo/g.test(state.url) && user === null) {
            this.router.navigateByUrl('/auth/login');
            return false;
        }
        return true;
    }

}
